import { useState, useEffect } from 'react';
import { Form, Button, Card, Toast } from '@douyinfe/semi-ui';
import { IconUser, IconLock, IconMail, IconPhone } from '@douyinfe/semi-icons';
import { motion } from 'framer-motion';
import { authApi, LoginRequest, RegisterRequest } from '../api/auth';
import { useNavigate, useLocation } from 'react-router-dom';

const Auth = () => {
  const location = useLocation();
  const [activeTab, setActiveTab] = useState<'login' | 'register'>(
    location.pathname === '/register' ? 'register' : 'login'
  );
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 监听路由变化，更新选项卡状态
  useEffect(() => {
    setActiveTab(location.pathname === '/register' ? 'register' : 'login');
  }, [location.pathname]);

  const handleLogin = async (values: LoginRequest) => {
    setLoading(true);
    try {
      const response = await authApi.login(values);
      
      // 保存token
      localStorage.setItem('token', response.token);
      
      // 获取用户信息
      const userInfo = await authApi.getUserInfo();
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      
      Toast.success('登录成功');
      navigate('/dashboard');
    } catch (error) {
      console.error('登录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (values: RegisterRequest) => {
    setLoading(true);
    try {
      // 验证密码确认
      if (values.password !== values.confirmPassword) {
        Toast.error('两次输入的密码不一致');
        return;
      }

      await authApi.register(values);
      Toast.success('注册成功，请登录');
      setActiveTab('login');
    } catch (error) {
      console.error('注册失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-500 via-purple-500 to-pink-500 flex items-center justify-center p-4 relative overflow-hidden">
      {/* 背景装饰元素 */}
      <div className="absolute inset-0 overflow-hidden">
        <motion.div
          className="absolute -top-40 -right-40 w-80 h-80 bg-white/10 rounded-full blur-3xl"
          animate={{
            x: [0, 100, 0],
            y: [0, -100, 0],
          }}
          transition={{
            duration: 20,
            repeat: Infinity,
            ease: "linear"
          }}
        />
        <motion.div
          className="absolute -bottom-40 -left-40 w-80 h-80 bg-white/10 rounded-full blur-3xl"
          animate={{
            x: [0, -100, 0],
            y: [0, 100, 0],
          }}
          transition={{
            duration: 25,
            repeat: Infinity,
            ease: "linear"
          }}
        />
        <motion.div
          className="absolute top-1/2 left-1/2 w-60 h-60 bg-white/5 rounded-full blur-3xl"
          animate={{
            scale: [1, 1.2, 1],
            rotate: [0, 180, 360],
          }}
          transition={{
            duration: 30,
            repeat: Infinity,
            ease: "linear"
          }}
        />
      </div>

      {/* 主要内容 */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6 }}
        className="relative z-10 w-full max-w-md"
      >
        <Card className="backdrop-blur-xl bg-white/10 border border-white/20 shadow-2xl rounded-3xl p-8">
          {/* 选项卡切换 */}
          <div className="flex mb-8 bg-white/10 rounded-2xl p-1">
            <button
              onClick={() => {
                setActiveTab('login');
                navigate('/login');
              }}
              className={`flex-1 py-3 px-6 rounded-xl text-sm font-medium transition-all duration-300 ${
                activeTab === 'login'
                  ? 'bg-white text-gray-800 shadow-lg'
                  : 'text-white/80 hover:text-white hover:bg-white/10'
              }`}
            >
              Login
            </button>
            <button
              onClick={() => {
                setActiveTab('register');
                navigate('/register');
              }}
              className={`flex-1 py-3 px-6 rounded-xl text-sm font-medium transition-all duration-300 ${
                activeTab === 'register'
                  ? 'bg-white text-gray-800 shadow-lg'
                  : 'text-white/80 hover:text-white hover:bg-white/10'
              }`}
            >
              Sign up
            </button>
          </div>

          {/* 登录表单 */}
          {activeTab === 'login' && (
            <motion.div
              key="login"
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: 20 }}
              transition={{ duration: 0.3 }}
            >
              <Form
                onSubmit={handleLogin}
                className="space-y-6"
              >
                  {/* <Form.Input
                    field="email"
                    placeholder="Enter your email"
                    prefix={<IconMail className="text-white/60" />}
                    className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入正确的邮箱格式' }
                    ]}
                  /> */}
                <Form.Input
                  field="username"
                  placeholder="Enter your name"
                  prefix={<IconUser className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入用户名' },
                    { min: 2, message: '用户名至少2位' }
                  ]}
                />
                <Form.Input
                  field="password"
                  type="password"
                  placeholder="Enter your password"
                  prefix={<IconLock className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6位' }
                  ]}
                />

                <Button
                  htmlType="submit"
                  loading={loading}
                  className="w-full bg-blue-600 hover:bg-blue-700 border-0 text-white font-medium rounded-xl h-12 text-base transition-all duration-300 transform hover:scale-105"
                >
                  Login
                </Button>
              </Form>
            </motion.div>
          )}

          {/* 注册表单 */}
          {activeTab === 'register' && (
            <motion.div
              key="register"
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <Form
                onSubmit={handleRegister}
                className="space-y-4"
              >
                <Form.Input
                  field="username"
                  placeholder="Enter your name"
                  prefix={<IconUser className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入用户名' },
                    { min: 2, message: '用户名至少2位' }
                  ]}
                />
                <Form.Input
                  field="password"
                  type="password"
                  placeholder="Enter your password"
                  prefix={<IconLock className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6位' }
                  ]}
                />

                <Form.Input
                  field="confirmPassword"
                  type="password"
                  placeholder="Confirm your password"
                  prefix={<IconLock className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请确认密码' }
                  ]}
                />

                {/* 真实姓名 */}
                <Form.Input
                  field="realName"
                  placeholder="Enter your real name"
                  prefix={<IconUser className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入真实姓名' },
                    { min: 2, message: '真实姓名至少2位' }
                  ]}
                />

                {/* 邮箱 */}
                <Form.Input
                  field="email"
                  placeholder="Enter your email"
                  prefix={<IconMail className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入正确的邮箱格式' }
                  ]}
                />

                {/* 手机号 */}
                <Form.Input
                  field="mobile"
                  placeholder="Enter your phone number"
                  prefix={<IconPhone className="text-white/60" />}
                  className="w-full bg-white/10 border-white/20 text-white placeholder-white/50 rounded-xl h-12"
                  rules={[
                    { required: true, message: '请输入手机号' }
                  ]}
                />

                <Button
                  htmlType="submit"
                  loading={loading}
                  className="w-full bg-blue-600 hover:bg-blue-700 border-0 text-white font-medium rounded-xl h-12 text-base transition-all duration-300 transform hover:scale-105 mt-6"
                >
                  Sign up
                </Button>
              </Form>
            </motion.div>
          )}
        </Card>
      </motion.div>
    </div>
  );
};

export default Auth;